package com.baor.service.Impl;

import com.baor.base.config.TokenService;
import com.baor.base.domain.UserVO;
import com.baor.base.util.R;
import com.baor.base.util.RedisUtil;
import com.baor.security.LoginUser;
import com.baor.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private ReactiveAuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;

    @Override
    public Mono<R> login(UserVO vo) {
        Mono<Authentication> authenticate = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(vo.getUserName(), vo.getUserPassword())
        );
        Mono<LoginUser> loginUserMono = authenticate.map(x -> (LoginUser) x.getPrincipal());
        return loginUserMono.map(x -> {
            UserVO userVO = x.getUserVO();
            String token = tokenService.createToken(userVO);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("userVO", userVO);
            return R.ok(map);
        });
    }
}
